package com.shiyue.cqe.service.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.shiyue.cqe.bean.BaseTable;
import com.shiyue.cqe.bind.xml.bean.Column;
import com.shiyue.cqe.bind.xml.bean.Line;
import com.shiyue.cqe.bind.xml.bean.Table;
import com.shiyue.cqe.component.model.ColumnComponent;
import com.shiyue.cqe.dao.BaseTableRepository;
import com.shiyue.cqe.service.ParseTemplateService;
import com.shiyue.cqe.service.common.InputType;
import com.shiyue.cqe.service.common.TableHelper;

public class ParseTemplateServiceImpl implements ParseTemplateService {

	private final Log log = LogFactory.getLog(InitServiceImpl.class );
	private String jspTemplate = "";
	private String path = "";
	
	private BaseTableRepository tableRepository;
	
	public BaseTableRepository getTableRepository() {
		return tableRepository;
	}

	public void setTableRepository(BaseTableRepository tableRepository) {
		this.tableRepository = tableRepository;
	}
	
	public void modifyParseTable(List<Table> tables){
		if(tables == null || tables.isEmpty()){
			return ;
		}
		for(Table table : tables){
			if(table.getLines() == null || table.getLines().isEmpty()){
				continue;
			}
			BaseTable baseTable = tableRepository.getByName(table.getTable());
			if(!table.isDynamicUpdate()){
				if(baseTable != null){
					continue;
				}
			}
			if(baseTable == null){
				baseTable = new BaseTable();
				baseTable.setName(table.getTable());
				baseTable.setAddtime(new Date());
			}
			baseTable.setName(table.getShowName());
			baseTable.setSimpleName(table.getSimpleName());
			baseTable.setOrderNum(table.getOrderNum());
			if(baseTable.getId() <= 0){
				//tableRepository.add(baseTable);
			}else{
				tableRepository.update(baseTable);
			}
			this.parseLines(table,table.getLines());
		}
	}
	
	private void parseLines(Table table,List<Line> lines){
		String tableName = table.getTable();
		List<Column> databaseColumn = new ArrayList<Column>();
		StringBuilder sb = new StringBuilder("<DIV align='center'><FONT class='font-tb-head'>");
		sb.append(table.getShowName()).append("</FONT></DIV>");
		StringBuilder editSb = new StringBuilder("<DIV align='center'><FONT class='font-tb-head'>");
		editSb.append(table.getShowName()).append("</FONT></DIV>");
		editSb.append("<br/><TABLE width='750px'  border='0' align='center' cellpadding='0' cellspacing='1' bordercolor='#999999' bgcolor='#999999' class='f12'>\r\n");
		sb.append("<br/><TABLE width='750px'  border='0' align='center' cellpadding='0' cellspacing='1' bordercolor='#999999' bgcolor='#999999' class='f12'>\r\n");
		for(Line line : lines){
			List<Column> columns = line.getColumns();
			if(columns == null){
				continue;
			}
			sb.append("\t<TR bgcolor='#FFFFFF'>\r\n");
			editSb.append("\t<TR bgcolor='#FFFFFF'>\r\n");
			for(Column column:columns){
				if(column.isDataBaseColumn() && StringUtils.equals("archives", column.getNature())){
					databaseColumn.add(column);
				}
				createTD(column,sb,tableName);
				createEditTD(column,editSb,tableName);
			}
			sb.append("\t</TR>\r\n");
			editSb.append("\t</TR>\r\n");
		}
		sb.append("</TABLE>");
		editSb.append("</TABLE>");
		if(StringUtils.isNotBlank(table.getDes())){
			sb.append("<br/><TABLE cellSpacing='0' cellPadding='0' width='750px' align='center' border='0'>");
			sb.append("<TR><TD vAlign=top align=right width=60>&nbsp;说明:</TD><TD style='text-align:left'>");
			sb.append(table.getDes().replaceAll("@newline", "<br/>"));
			sb.append("</TD></TR></TABLE>");
			editSb.append("<br/><TABLE cellSpacing='0' cellPadding='0' width='750px' align='center' border='0'>");
			editSb.append("<TR><TD vAlign=top align=right width=60>&nbsp;说明:</TD><TD style='text-align:left'>");
			editSb.append(table.getDes().replaceAll("@newline", "<br/>"));
			editSb.append("</TD></TR></TABLE>");
		}
		createTemplateJSP(tableName,sb.toString());
		createTemplateJSP(tableName + "edit",editSb.toString());
		this.createDataBaseTable(tableName, databaseColumn);
	}
	
	private void createTemplateJSP(String tableName,String talbeDetail){
		if(StringUtils.isBlank(jspTemplate)){
			loadBaseTemplate();
		}
		String filePath = path.substring(0,path.indexOf("WEB-INF"));
		FileOutputStream fos = null;
		Writer out = null;
		try {
			String template = jspTemplate.replaceAll("#title#", tableName);
			template = template.replaceAll("#body#",talbeDetail);
			fos = new FileOutputStream(new File(filePath + "cqe/template/" + tableName + ".jsp"));
			out = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
			out.write(template);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(fos != null){
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
	}
	
	private void loadBaseTemplate(){
		if(StringUtils.isBlank(path)){
			path = ParseTemplateServiceImpl.class.getResource("/").toString().replaceAll("file:", "");
		}
		File file = new File(path + "template/baseJspTemplate/baseTemplate.jsp");
		FileInputStream fis = null;
		BufferedReader br  = null;
		try {
			fis = new FileInputStream(file);
			br = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
			String str = "";
			StringBuilder sb = new StringBuilder();
			while(str != null){
				str = br.readLine();
				if(str!=null){
					sb.append(str).append("\r\n");
				}
			}
			jspTemplate = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fis != null){
				try {
					fis.close();
				} catch (IOException e) {
				}
			}
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
				}
			}
		}
	}
	
	private void createDataBaseTable(String tableName,List<Column> columns){
		List<ColumnComponent> columnComponents = new ArrayList<ColumnComponent>();
		ColumnComponent component = new ColumnComponent();
		component.setName("id");
		component.setNotNull(true);
		component.setPrimary(true);
		component.setType("long");
		columnComponents.add(component);
		for(Column column : columns){
			ColumnComponent components = new ColumnComponent();
			components.setDefalutValue(column.getDefaultValue());
			components.setType(column.getType());
			components.setDescription(column.getDes());
			if(StringUtils.isNotBlank(column.getMaxLength())){
				components.setLength(Integer.parseInt(column.getMaxLength()));
			}
			components.setName(column.getName());
			components.setNotNull(column.isNotNull());
			columnComponents.add(components);
		}
		String sql = TableHelper.buildCreateTableSql(tableName, columnComponents);
		log.info(sql);
		//tableRepository.excuteSQL(sql);
	}
	
	private void createTD(Column column,StringBuilder sb,String tableName){
			sb.append("\t\t<TD colSpan='").append(column.getColSpan()).append("' rowSpan='").append(column.getRowSpan())
				.append("' ");
			if(StringUtils.isNotBlank(column.getWidth())){
				sb.append("width='").append(column.getWidth()).append("' ");
			}
			if(StringUtils.isNotBlank(column.getHeight())){
				sb.append("height='").append(column.getHeight()).append("' ");
			}
			sb.append(">\r\n\t\t\t\t");
			if(!column.isDataBaseColumn()){
				sb.append(column.getShowName());
			}else if(StringUtils.equals("archives", column.getNature())){
				if(column.getControlsType().toLowerCase().equals("textarea") && StringUtils.isNotBlank(column.getShowName())){
					sb.append(column.getShowName()).append("<br/>");
				}
				sb.append("\\${").append(tableName).append("Map.").append(column.getName()).append("}");
			}else if(StringUtils.equals("appraise", column.getNature()) && column.isHeap()){
				sb.append(column.getShowName()).append("<br/>").append("<c:forEach var=\"appraise\" items=\"\\${appraises.")
					.append(column.getName()).append("}\">\\${appraise.appraiseValue}</c:forEach>");
			}else{
				sb.append("\\${appraises.").append(column.getName()).append("[0].appraiseValue}");
			}
			sb.append("\r\n\t\t</TD>\r\n");
	}

	private void createEditTD(Column column,StringBuilder sb,String tableName){
		sb.append("\t\t<TD colSpan='").append(column.getColSpan()).append("' rowSpan='").append(column.getRowSpan())
			.append("' ");
		if(StringUtils.isNotBlank(column.getWidth())){
			sb.append("width='").append(column.getWidth()).append("' ");
		}
		if(StringUtils.isNotBlank(column.getHeight())){
			sb.append("height='").append(column.getHeight()).append("' ");
		}
		sb.append(">\r\n\t\t\t\t");
		if(!column.isDataBaseColumn()){
			sb.append(column.getShowName());
		}else if(StringUtils.equals("archives", column.getNature())){
			if(column.getControlsType().toLowerCase().equals("textarea") && StringUtils.isNotBlank(column.getShowName())){
				sb.append(column.getShowName()).append("<br/>");
			}
			sb.append(TableHelper.getInput(Enum.valueOf(InputType.class,column.getControlsType().toUpperCase()),"\\${" + tableName + "Map." + column.getName() + "}"
					,composeInputAttribute(column), column.getControlsName()));
		}else if(StringUtils.equals("appraise", column.getNature()) && column.isHeap()){
			sb.append(column.getShowName()).append("<br/>").append("<c:forEach var=\"appraise\" items=\"\\${appraises.")
				.append(column.getName()).append("}\">\\${appraise.appraiseValue}</c:forEach>");
			sb.append(TableHelper.getInput(Enum.valueOf(InputType.class,column.getControlsType().toUpperCase()),"", 
					composeInputAttribute(column), column.getControlsName()));
		}else{
			sb.append(TableHelper.getInput(Enum.valueOf(InputType.class,column.getControlsType().toUpperCase()),"\\${appraises." + column.getName() + "[0].appraiseValue}", 
					composeInputAttribute(column), column.getControlsName()));
		}
		sb.append("\r\n\t\t</TD>\r\n");
	}
	
	private String composeInputAttribute(Column column){
		StringBuilder attribute = new StringBuilder(); 
		attribute.append(" name='").append(column.getName()).append("' id='").append(column.getName()).append("'");
		if(StringUtils.isNotBlank(column.getCols())){
			attribute.append(" cols='").append(column.getCols()).append("'");
		}
		if(StringUtils.isNotBlank(column.getRows())){
			attribute.append(" rows='").append(column.getRows()).append("'");
		}
		if(StringUtils.isNotBlank(column.getMaxLength())){
			attribute.append(" maxlength='").append(column.getMaxLength()).append("'");
		}
		if(StringUtils.isNotBlank(column.getMinValue())){
			attribute.append(" minValue='").append(column.getMinValue()).append("'");
		}
		if(StringUtils.isNotBlank(column.getMaxValue())){
			attribute.append(" maxValue='").append(column.getMaxValue()).append("'");
		}
		return attribute.toString();
	}
}
